#include "led_control_center.h"

LEDControlCenter::LEDControlCenter(LEDManager* manager) {
    ledManager = manager;
    currentRequestedStatus = LED_OFF;
    lastConfirmedStatus = LED_OFF;
    lastStatusChangeTime = 0;
    
    drawingSessionActive = false;
    temporaryOverrideActive = false;
    temporaryOverrideStatus = LED_OFF;
    temporaryOverrideExpiry = 0;
    
    consecutiveFailures = 0;
}

LEDControlCenter::~LEDControlCenter() {
    // 析构函数 - 不删除ledManager，因为它由外部管理
}

bool LEDControlCenter::begin() {
    if (!ledManager) {
        Serial.println("❌ LEDControlCenter初始化失败：LEDManager为空");
        return false;
    }
    
    initializePriorities();
    
    Serial.println("✅ LED控制中心初始化成功");
    Serial.println("🎯 LED状态管理架构:");
    Serial.println("   应用层 → LEDControlCenter → LEDManager → 硬件");
    Serial.println("   ✅ 业务逻辑  ✅ 硬件抽象  ✅ 物理控制");
    
    return true;
}

void LEDControlCenter::initializePriorities() {
    // 设置状态优先级（数字越大优先级越高）
    statusPriority[LED_OFF] = 0;
    statusPriority[LED_STARTUP] = 1;
    statusPriority[LED_INITIALIZING] = 2;
    statusPriority[LED_WIFI_CONNECTING] = 3;
    statusPriority[LED_WIFI_CONNECTED] = 4;
    statusPriority[LED_WIFI_FAILED] = 5;
    statusPriority[LED_IDLE] = 6;
    statusPriority[LED_HOMING] = 8;          // 归零优先级高
    statusPriority[LED_DRAWING] = 7;         // 绘图优先级中等
    statusPriority[LED_PAUSED] = 7;          // 暂停优先级中等
    statusPriority[LED_COMPLETED] = 6;       // 完成状态优先级低
    statusPriority[LED_ERROR] = 9;           // 错误状态优先级很高
    statusPriority[LED_EMERGENCY] = 10;      // 紧急状态最高优先级
}

void LEDControlCenter::update() {
    unsigned long currentTime = millis();
    
    // 处理临时覆盖状态的过期
    if (temporaryOverrideActive && currentTime > temporaryOverrideExpiry) {
        clearTemporaryOverride();
    }
    
    // 处理自动状态切换逻辑
    if (currentRequestedStatus == LED_STARTUP && currentTime - lastStatusChangeTime > 2000) {
        requestStatusChange(LED_IDLE, "启动状态自动切换");
    }
    
    // 确保LEDManager持续更新
    if (ledManager) {
        ledManager->update();
    }
}

bool LEDControlCenter::requestStatusChange(LEDStatus status, const String& reason) {
    if (!ledManager) {
        Serial.println("❌ LED控制中心：LEDManager不可用");
        return false;
    }
    
    // 绘图会话期间只允许特定状态切换
    if (drawingSessionActive && status != LED_DRAWING && status != LED_PAUSED && 
        status != LED_COMPLETED && status != LED_ERROR && status != LED_EMERGENCY) {
        Serial.printf("⚠️ LED控制中心：绘图会话期间拒绝状态切换到 %d\n", status);
        return false;
    }
    
    // 检查临时覆盖状态
    if (temporaryOverrideActive) {
        Serial.printf("⚠️ LED控制中心：临时覆盖期间拒绝状态切换到 %d\n", status);
        return false;
    }
    
    // 检查状态转换是否合法
    if (!canTransitionTo(status)) {
        Serial.printf("⚠️ LED控制中心：不允许从 %d 切换到 %d\n", currentRequestedStatus, status);
        return false;
    }
    
    // 执行状态切换
    LEDStatus oldStatus = currentRequestedStatus;
    currentRequestedStatus = status;
    
    // 调用硬件层执行
    ledManager->setStatus(status);
    
    // 记录状态变化
    logStatusChange(oldStatus, status, reason);
    lastStatusChangeTime = millis();
    lastConfirmedStatus = status;
    
    return true;
}

bool LEDControlCenter::canTransitionTo(LEDStatus newStatus) {
    // 紧急状态和错误状态总是可以切换
    if (newStatus == LED_EMERGENCY || newStatus == LED_ERROR) {
        return true;
    }
    
    // 检查优先级
    int currentPriority = statusPriority[currentRequestedStatus];
    int newPriority = statusPriority[newStatus];
    
    // 高优先级可以打断低优先级，但要有合理的理由
    if (newPriority >= currentPriority) {
        return true;
    }
    
    // 特殊规则：某些状态转换是被允许的
    switch (currentRequestedStatus) {
        case LED_DRAWING:
            // 绘图状态可以切换到暂停、完成或空闲
            return (newStatus == LED_PAUSED || newStatus == LED_COMPLETED || newStatus == LED_IDLE);
            
        case LED_PAUSED:
            // 暂停状态可以切换到绘图或空闲
            return (newStatus == LED_DRAWING || newStatus == LED_IDLE);
            
        case LED_HOMING:
            // 归零状态可以切换到空闲、绘图、维护状态
            return (newStatus == LED_IDLE || newStatus == LED_DRAWING || newStatus == LED_MAINTENANCE);
            
        case LED_COMPLETED:
            // 🔧 修改：完成状态允许接受任何合理的新指令
            // 完成状态不会自动切换，只有接收到新指令时才会改变
            // 除了错误和紧急状态（它们有特殊处理逻辑），其他状态都允许
            return (newStatus != LED_ERROR && newStatus != LED_EMERGENCY);
            
        case LED_IDLE:
            // 空闲状态可以切换到任何状态（WiFi连接、归零、绘图等）
            return true;
            
        case LED_WIFI_CONNECTING:
            // WiFi连接中可以切换到连接成功、失败或空闲
            return (newStatus == LED_WIFI_CONNECTED || newStatus == LED_WIFI_FAILED || newStatus == LED_IDLE);
            
        case LED_WIFI_CONNECTED:
            // WiFi连接成功后可以切换到其他状态
            return true;
            
        case LED_WIFI_FAILED:
            // WiFi连接失败后可以重新尝试连接或进入其他状态
            return true;
            
        case LED_MAINTENANCE:
            // 维护状态可以切换到任何状态（维护权限最高）
            return true;
            
        default:
            return false;
    }
}

void LEDControlCenter::logStatusChange(LEDStatus from, LEDStatus to, const String& reason) {
    String statusNames[] = {"OFF", "STARTUP", "INITIALIZING", "WIFI_CONNECTING", 
                           "WIFI_CONNECTED", "WIFI_FAILED", "IDLE", "HOMING", 
                           "DRAWING", "PAUSED", "COMPLETED", "ERROR", "MAINTENANCE", "EMERGENCY"};
    
    String fromName = (from < 14) ? statusNames[from] : "UNKNOWN";
    String toName = (to < 14) ? statusNames[to] : "UNKNOWN";
    
    Serial.printf("🎛️ LED控制中心：%s → %s", fromName.c_str(), toName.c_str());
    if (reason.length() > 0) {
        Serial.printf(" (原因: %s)", reason.c_str());
    }
    Serial.println();
}

LEDStatus LEDControlCenter::getCurrentStatus() {
    return currentRequestedStatus;
}

void LEDControlCenter::startDrawingSession() {
    drawingSessionActive = true;
    
    if (ledManager) {
        // 启动LEDManager的绘图会话
        ledManager->startDrawingSession();
        
        // 设置默认值（如果需要）
        if (ledManager->getDrawingBrightness() == 0) {
            ledManager->setDrawingBrightness(200);
        }
        if (ledManager->getDrawingSpeed() == 0) {
            ledManager->setDrawingSpeed(5);
        }
        
        // 立即应用效果
        ledManager->update();
        
        Serial.println("🎨 绘图会话已启动");
    }
    
    // 切换到绘图状态
    requestStatusChange(LED_DRAWING, "开始绘图会话");
}

void LEDControlCenter::endDrawingSession() {
    drawingSessionActive = false;
    requestStatusChange(LED_COMPLETED, "结束绘图会话");
    
    // 调用LEDManager的绘图会话结束方法
    if (ledManager) {
        ledManager->endDrawingSession();
    }
    
    Serial.println("✅ LED控制中心：绘图会话已结束 - 状态已解锁");
}

bool LEDControlCenter::isDrawingSessionActive() {
    return drawingSessionActive;
}

void LEDControlCenter::setTemporaryOverride(LEDStatus status, unsigned long durationMs) {
    temporaryOverrideActive = true;
    temporaryOverrideStatus = status;
    temporaryOverrideExpiry = millis() + durationMs;
    
    // 直接设置临时状态（绕过优先级检查）
    if (ledManager) {
        ledManager->setTemporaryColor(LEDColor(255, 255, 0), 200);  // 黄色临时提示
    }
    
    Serial.printf("⏰ LED控制中心：临时覆盖状态 %d，持续 %lums\n", status, durationMs);
}

void LEDControlCenter::clearTemporaryOverride() {
    if (temporaryOverrideActive) {
        temporaryOverrideActive = false;
        
        if (ledManager) {
            ledManager->clearTemporaryColor();
        }
        
        Serial.println("🔄 LED控制中心：临时覆盖状态已清除");
    }
}

// 移除：LED健康检查功能 - 意义不大，增加不必要的复杂性
/*
bool LEDControlCenter::performHealthCheck() {
    if (!ledManager) {
        return false;
    }
    
    // 检查LEDManager健康状态
    bool healthy = ledManager->isWS2812Healthy();
    
    if (healthy) {
        consecutiveFailures = 0;
    } else {
        consecutiveFailures++;
        Serial.printf("⚠️ LED健康检查失败，连续失败次数: %d\n", consecutiveFailures);
    }
    
    return healthy;
}
*/

// 移除：LED故障处理功能 - 配合健康检查功能一起移除
/*
void LEDControlCenter::handleFailure() {
    if (consecutiveFailures >= 3) {
        Serial.println("🚨 LED控制中心：检测到严重故障，执行紧急重置");
        emergencyReset();
    }
}
*/

// 移除：LED维护功能 - 配合健康检查功能一起移除
/*
void LEDControlCenter::performMaintenance() {
    Serial.println("🔧 LED控制中心：执行维护操作...");
    
    if (ledManager) {
        ledManager->resetWS2812();
    }
    
    consecutiveFailures = 0;
    lastHealthCheck = millis();
    
    Serial.println("✅ LED维护完成");
}
*/

void LEDControlCenter::emergencyReset() {
    Serial.println("🚨 LED控制中心：执行紧急重置");
    
    // 清除所有状态
    drawingSessionActive = false;
    temporaryOverrideActive = false;
    consecutiveFailures = 0;
    
    // 重置硬件（简化版本）
    if (ledManager) {
        ledManager->safeShutdown();
        delay(500);  // 减少延迟时间
        ledManager->begin();
    }
    
    // 设置安全状态
    requestStatusChange(LED_IDLE, "紧急重置完成");  // 改为IDLE而不是ERROR
    
    Serial.println("✅ LED紧急重置完成");
}

String LEDControlCenter::getStatusReport() {
    String report = "=== LED控制中心状态报告 ===\n";
    
    String statusNames[] = {"OFF", "STARTUP", "INITIALIZING", "WIFI_CONNECTING", 
                           "WIFI_CONNECTED", "WIFI_FAILED", "IDLE", "HOMING", 
                           "DRAWING", "PAUSED", "COMPLETED", "ERROR", "EMERGENCY"};
    
    String currentName = (currentRequestedStatus < 13) ? statusNames[currentRequestedStatus] : "UNKNOWN";
    report += "当前状态: " + currentName + "\n";
    report += "绘图会话: " + String(drawingSessionActive ? "活跃" : "非活跃") + "\n";
    report += "临时覆盖: " + String(temporaryOverrideActive ? "是" : "否") + "\n";

    
    if (lastStatusChangeTime > 0) {
        unsigned long timeSinceChange = millis() - lastStatusChangeTime;
        report += "上次状态变化: " + String(timeSinceChange / 1000) + " 秒前\n";
    }
    
    return report;
}

void LEDControlCenter::updateSystemStatus(bool systemPowerEnabled, bool isDrawingActive, bool isDrawingPaused) {
    // 🎯 这是替代直接调用LEDManager的关键方法
    
    if (!systemPowerEnabled) {
        requestStatusChange(LED_OFF, "系统电源关闭");
        return;
    }
    
    // 🔥 重要修复：不要覆盖高优先级状态（如HOMING, ERROR等）
    // 只有在当前状态允许时才进行绘图相关的状态切换
    LEDStatus current = getCurrentStatus();
    
    // 如果当前是高优先级状态（归零、错误等），不要被系统状态覆盖
    if (current == LED_HOMING || current == LED_ERROR || current == LED_EMERGENCY || 
        current == LED_INITIALIZING || current == LED_WIFI_CONNECTING) {
        // 这些状态由其他逻辑控制，不应被系统状态覆盖
        return;
    }
    
    if (isDrawingActive) {
        if (!drawingSessionActive) {
            startDrawingSession();
        }
    } else if (isDrawingPaused) {
        // 🔧 修复：暂停状态时保持绘图会话活跃，不要结束会话
        if (current != LED_PAUSED) {
            requestStatusChange(LED_PAUSED, "绘图暂停");
        }
        // 重要：暂停时不调用endDrawingSession()，保持会话活跃
    } else {
        if (drawingSessionActive) {
            endDrawingSession();
        } else {
            // 只有在低优先级状态时才切换到空闲
            if (current == LED_IDLE || current == LED_COMPLETED || 
                current == LED_WIFI_CONNECTED || current == LED_WIFI_FAILED || 
                current == LED_PAUSED) {
                requestStatusChange(LED_IDLE, "系统空闲");
            }
        }
    }
}

// 移除：LED健康检查功能 - 简化代码，直接返回基本状态
bool LEDControlCenter::isHealthy() {
    return ledManager != nullptr;
}

unsigned long LEDControlCenter::getLastStatusChangeTime() {
    return lastStatusChangeTime;
}

String LEDControlCenter::getStatusHistory() {
    // 这里可以实现状态历史记录功能
    return "状态历史记录功能待实现";
}

// ==================== 统一接口方法实现 ====================

void LEDControlCenter::enableWS2812(bool enable) {
    if (ledManager) {
        ledManager->enableWS2812(enable);
        Serial.printf("🎛️ LED控制中心：WS2812 %s\n", enable ? "启用" : "禁用");
    }
}

void LEDControlCenter::enableStatusLed(bool enable) {
    if (ledManager) {
        ledManager->enableStatusLed(enable);
        Serial.printf("🎛️ LED控制中心：状态LED %s\n", enable ? "启用" : "禁用");
    }
}

bool LEDControlCenter::isWS2812Enabled() {
    return ledManager ? ledManager->isWS2812Enabled() : false;
}

bool LEDControlCenter::isWS2812Healthy() {
    // 简化：直接返回LEDManager是否可用，移除复杂的健康检查逻辑
    return ledManager != nullptr;
}

void LEDControlCenter::setTemporaryColor(LEDColor color, uint8_t brightness) {
    if (ledManager) {
        ledManager->setTemporaryColor(color, brightness);
        Serial.printf("🎛️ LED控制中心：临时颜色 RGB(%d,%d,%d), 亮度=%d\n", 
                      color.r, color.g, color.b, brightness);
    }
}

void LEDControlCenter::clearTemporaryColor() {
    if (ledManager) {
        ledManager->clearTemporaryColor();
        Serial.println("🎛️ LED控制中心：临时颜色已清除");
    }
}

void LEDControlCenter::setGlobalBrightness(uint8_t brightness) {
    if (ledManager) {
        ledManager->setGlobalBrightness(brightness);
        Serial.printf("🎛️ LED控制中心：全局亮度设置为 %d%%\n", (brightness * 100) / 255);
    }
}

uint8_t LEDControlCenter::getGlobalBrightness() {
    return ledManager ? ledManager->getGlobalBrightness() : 0;
}

void LEDControlCenter::setDrawingEffect(LEDEffectMode mode, LEDColor color) {
    if (ledManager) {
        ledManager->setDrawingEffect(mode, color);
        Serial.printf("🎛️ LED控制中心：绘图效果设置 - 模式=%d, 颜色=RGB(%d,%d,%d)\n", 
                      mode, color.r, color.g, color.b);
    }
}

void LEDControlCenter::setDrawingBrightness(uint8_t brightness) {
    if (ledManager) {
        ledManager->setDrawingBrightness(brightness);
        Serial.printf("🎛️ LED控制中心：绘图亮度设置为 %d%%\n", (brightness * 100) / 255);
    }
}

void LEDControlCenter::setDrawingSpeed(uint8_t speed) {
    if (ledManager) {
        ledManager->setDrawingSpeed(speed);
        Serial.printf("🎛️ LED控制中心：绘图速度设置为 %d\n", speed);
    }
}

void LEDControlCenter::updatePosition(float theta, float rho) {
    if (ledManager) {
        ledManager->updatePosition(theta, rho);
        // 位置更新频率较高，不输出日志避免日志过多
    }
}

LEDStatus LEDControlCenter::getLEDStatus() {
    return currentRequestedStatus;
}
